package com.abeir.bilibili.convert;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.Optional;

public class AudioScanner extends AbstractMediaScanner {

    public AudioScanner(String playurlFilename, String suffix) {
        super(playurlFilename, suffix);
    }

    @Override
    public Optional<String> findBaseUrlFromJSON(JSONObject rootJSONObject) {
        JSONObject dataObject = rootJSONObject.getJSONObject("data");
        if(dataObject == null){
            throw new IllegalArgumentException("Not data element found in JSON.");
        }
        JSONObject dashObject = dataObject.getJSONObject("dash");
        if(dashObject == null){
            throw new IllegalArgumentException("Not dash element found in JSON.");
        }
        JSONArray audioArray = dashObject.getJSONArray("audio");
        if (audioArray == null || audioArray.isEmpty()){
            throw new IllegalArgumentException("Not audio element found in JSON.");
        }
        JSONObject audioObject = audioArray.getJSONObject(0);
        if(audioObject == null){
            throw new IllegalArgumentException("Not audio element found in JSON.");
        }
        String baseUrl = audioObject.getString("baseUrl");
        if(baseUrl == null || baseUrl.isEmpty()){
            baseUrl = audioObject.getString("base_url");
        }
        return Optional.ofNullable(baseUrl);
    }
}
